package xin.nick.system.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import xin.nick.common.core.util.UserIdUtil;
import xin.nick.system.entity.SystemUser;
import xin.nick.system.manager.SystemUserManager;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 用于设置用户Id的过滤器
 * @author Nick
 * @since 2023/12/11
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserIdFilter extends OncePerRequestFilter {

    private final SystemUserManager systemUserManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        Long userId = null;

        // 从权限上下文获取验证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 如果是认证正常的用户,则设置用户ID

        if (Objects.nonNull(authentication) && authentication.isAuthenticated()) {
            UserDetails user = (UserDetails)authentication.getPrincipal();
            SystemUser systemUser = systemUserManager.getUserByUsername(user.getUsername());
            if (Objects.nonNull(systemUser)) {
                userId = systemUser.getUserId();
            }
        }

        // 设置全局 userId
        UserIdUtil.setUserId(userId);

        log.debug("userId: {}", userId);

        // 往下一个过滤器走
        filterChain.doFilter(request, response);

        // 处理完去掉 userId 信息
        UserIdUtil.removeUserId();
    }
}
